<?php
/**
 * Created by PhpStorm.
 * User: zeopean
 * Date: 2015/8/6
 * Time: 11:51
 */
namespace App\Http\Controllers\Api;

use App\District;
use App\Exceptions\InvestorException;
use App\Fields;
use App\Http\Requests\InvestOrgRequest;
use App\Http\Requests\InvestorRequest;
use App\Http\Requests\InvestLogRequest;
use App\Exceptions\SecurityException;
use App\Exceptions\InvestLogException;
use App\Investor;
use App\InvestLog;
use App\InvestOrg;
use App\Phases;
use App\ProjectUrl;
use App\User;
use App\UserInfo;
use Illuminate\Auth\Guard;
use Illuminate\Support\Facades\Input;

class InvestController extends ApiController
{

    /**
     * @param InvestorRequest $request
     */
    public function EditInvestor(Guard $guard, InvestorRequest $request, $id = 0)
    {
        /** 判断用户是否登录*/
        if ($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        /** @var User $currentUser */
        $currentUser = $guard->user();
        if (!$currentUser)
            throw new SecurityException(SecurityException::NoPermission);

        /**对字段进行过滤 判断   比较金额大小**/
        if ($id != 0 && Investor::whereId($id)->exists()) {
            $Investor = Investor::find($id);
        } else {
            $Investor = new Investor();
        }

        /** 数据提交 */
        if (!is_null($request->get('org_id'))) $Investor->org_id = $request->get('org_id');
        if (!is_null($request->get('user_id'))) $Investor->user_id = $request->get('user_id');
        if (!is_null($request->get('invest_log_id'))) $Investor->invest_log_id = $request->get('invest_log_id');
        if (!is_null($request->get('invest_fields'))) $Investor->invest_fields = $request->get('invest_fields');
        if (!is_null($request->get('invest_phase'))) $Investor->invest_phase = $request->get('invest_phase');
        if (!is_null($request->get('invest_num_small'))) $Investor->invest_num_small = $request->get('invest_num_small');
        if (!is_null($request->get('invest_num_big'))) $Investor->invest_num_big = $request->get('invest_num_big');
        $Investor->status = 0;

        $Investor->save();

        return $this->buildResponse(trans('inv.edit-investor.success'), $Investor);
    }

    /**
     * 投资经历编辑
     *
     * @param Guard $guard
     * @param InvestLogRequest $request
     * @param $id
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     * @throws SecurityException
     */
    public function EditInvestLog(Guard $guard, InvestLogRequest $request, $id = 0)
    {
        /** 判断用户是否登录 */
        if ($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);
        /** @var User $currentUser */
        $currentUser = $guard->user();
        if (!$currentUser)
            throw new SecurityException(SecurityException::NoPermission);

        if ($id != 0 && InvestLog::whereId($id)->exists()) {
            $InvestLog = InvestLog::find($id);
        } else if (!InvestLog::whereId($id)->exists()) {
            $InvestLog = new InvestLog();
        }

        /** 接收数据       */
        $userId     = $request->get('user_id');
        $orgId      = $request->get('org_id');
        $projectId  = $request->get('project_id');
        $moneyNum   = $request->get('money_num');
        $moneyDesc  = $request->get('money_desc');
        $moneyType  = $request->get('money_type');
        $stockNum   = $request->get('stock_num');
        $investTime = $request->get('invest_time');
        $investAccount      = $request->get('invest_account');
        $isOnlineFinance    = $request->get('is_online_finance');
        $isLead     = $request->get('is_lead');

        if (is_null($userId) && is_null($orgId))
            throw new InvestLogException(InvestLogException::NoUserIdAndOrgId);

        /** 对数据进行判断 */
        if (!is_null($userId))      $InvestLog->user_id = $userId;
        if (!is_null($orgId))       $InvestLog->org_id = $orgId;
        if (!is_null($projectId))   $InvestLog->project_id = $projectId;
        if (!is_null($moneyNum))    $InvestLog->money_num = $moneyNum;
        if (!is_null($moneyDesc))   $InvestLog->money_desc = $moneyDesc;
        if (!is_null($moneyType))   $InvestLog->money_type = $moneyType;
        if (!is_null($stockNum))    $InvestLog->stock_num = $stockNum;
        if (!is_null($investTime))  $InvestLog->invest_time = $investTime;
        if (!is_null($investAccount))   $InvestLog->invest_account = $investAccount;
        if (!is_null($isOnlineFinance)) $InvestLog->is_online_finance = $isOnlineFinance;
        if (!is_null($isLead))      $InvestLog->is_lead = $isLead;
        $InvestLog->status = 0;

        $InvestLog->save();

        return $this->buildResponse(trans('api.invest_log.success'), $InvestLog);
    }


    /**
     * 通过机构标识 进行投资机构 编辑
     * @param Guard $guard
     * @param InvestOrgRequest $request
     * @param int $id
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     * @throws SecurityException
     */
    public function EditInvestOrg(Guard $guard, InvestOrgRequest $request, $id = 0)
    {
        /** 判断用户是否登录 */
        if ($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        if ($id != 0)
            $investOrg = InvestOrg::find($id);
        else
            $investOrg = new InvestOrg();
        $min_quota = $request->get('min_quota');
        $max_quota = $request->get('max_quota');
        if (!is_null($request->get('invest_name'))) $investOrg->invest_name = $request->get('invest_name');
        if (!is_null($request->get('invest_desc'))) $investOrg->invest_desc = $request->get('invest_desc');
        if (!is_null($request->get('invest_money'))) $investOrg->invest_money = $request->get('invest_money');
        if (!empty($min_quota)) $investOrg->min_quota = $request->get('min_quota');
        if (!empty($max_quota)) $investOrg->max_quota = $request->get('max_quota');
        if (!is_null($request->get('wechat'))) $investOrg->wechat = $request->get('wechat');
        if (!is_null($request->get('weibo'))) $investOrg->weibo = $request->get('weibo');
        if (!is_null($request->get('begin_date'))) $investOrg->begin_date = $request->get('begin_date');
        if (!is_null($request->get('img_logo_id'))) $investOrg->img_logo_id = $request->get('img_logo_id');

        if (!is_null($request->get('web_link'))) {
            $projectUrl = ProjectUrl::firstOrCreate(['url_type' => 'web', 'url_name' => $request->get('web_link'),
                'project_id' => 0]);
            $investOrg->link_web_id = $projectUrl->id;
        }
        $investOrg->save();

        return $this->buildResponse(trans('api.edit-invest-org.success'), $investOrg);

    }

    /**
     * 获取更多的投资人信息
     * @return bool|\Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     */
    public function getInvestorMore()
    {
        $counts = User::whereRole(1)->whereStatus(1)->count('id');
        /** 总记录数 */
        $page = Input::get('page');
        /** 页数 */
        $offset = 0;
        if ($page != 0)
            $offset = $page * self::PAGE;

        if ($counts >= $offset) {
            $users = User::whereRole(1)->whereStatus(1)->skip($offset)->take(self::PAGE)->get();
            if (!$users) return false;

            foreach ($users as $user) {
                $user['userInfo'] = $user->userInfo;
                $user['fields'] = $user->getFieldsByUserId($user->id);
                $user['projects'] = $user->getInvestProjectByUserId($user->id);
                $user['account'] = $user->getInvestAreaByUserId($user->id);
            }

            return $this->buildResponse(trans('api.get_investor_more.success'), $users);
        }
    }

    /**
     * 获取更多的投资机构信息
     * @return bool|\Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     */
    public function getInvestOrgMore()
    {
        $counts = InvestOrg::whereStatus(1)->count('id');
        /** 总记录数 */
        $page = Input::get('page');
        /** 页数 */
        $offset = 0;
        if ($page != 0)
            $offset = $page * self::PAGE;

        if ($counts >= $offset) {
            $orgs = InvestOrg::whereStatus(1)->skip($offset)->take(self::PAGE)->get();
            if (!$orgs) return false;

            foreach ($orgs as $org) {
                $org['phases'] = $org->getPhasesByOrgId($org->id);
                $org['members'] = $org->getOrgMemberbyOrgId($org->id);
                $org['projects'] = $org->getProjectNameByOrgId($org->id);
            }
            return $this->buildResponse(trans('api.get_creater_more.success'), $orgs);
        }
    }


    /**
     * 通过标签搜索 投资人信息
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     */
    public function getInvestorMessageBySearch()
    {
        //接收参数
        $phaseId = Input::get('phase');
        $fieldId = Input::get('field');
        $dist = Input::get('dist');
        $keyword = Input::get('keyword');

        $investors = Investor::whereStatus(1);

        if (!empty($phaseId)) {
            $investors->join('phase_relations', 'phase_relations.investor_id', '=', 'investor.id');
            $investors->join('phases', 'phases.id', '=', 'phase_relations.phase_id');
            $investors->where('phases.id', '=', $phaseId);
        }

        if (!empty($fieldId)) {
            $investors->join('invest_fields', 'invest_fields.investor_id', '=', 'investor.id');
            $investors->join('fields', 'fields.id', '=', 'invest_fields.field_id');
            $investors->where('fields.id', '=', $fieldId);
        }


        if (!empty($dist)) {
            $investors->join('user_info', 'investor.user_id', '=', 'user_info.user_id');
            $investors->where('user_info.province', 'like', '%' . $dist . '%');
            $investors->orWhere('user_info.city', 'like', '%' . $dist . '%');
        }

        if (!empty($keyword)) {
            $investors->where('user_info.realname', 'like', '%' . $keyword . '%');
        }

        $investorsIds = $investors->select('investor.user_id')->lists('investor.user_id');

        if (!$investorsIds) return;
        /** 数据项为空  */
        $users = User::whereId($investorsIds)->get();

        foreach ($users as $user) {
            $user['userInfo'] = $user->userInfo;
            $user['fields'] = $user->getFieldsByUserId($user->id);
            $user['projects'] = $user->getInvestProjectByUserId($user->id);
            $user['account'] = $user->getInvestAreaByUserId($user->id);
        }

        return $this->buildResponse(trans('api.get_investor_more.success'), $users);

    }

    /**
     * 通过标签搜索 投资机构
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     */
    public function getInvestOrgMessageBySearch()
    {
        /** 接收参数 */
        $phaseId = Input::get('phase');
        $fieldId = Input::get('field');
        $dist = Input::get('dist');
        $keyword = Input::get('keyword');

        $orgs = InvestOrg::whereStatus(1);

        if (!empty($phaseId)) {
            $orgs->join('phase_relations', 'phase_relations.org_id', '=', 'invest_org.id');
            $orgs->join('phases', 'phases.id', '=', 'phase_relations.phase_id');
            $orgs->where('phases.id', '=', $phaseId);
        }

        if (!empty($fieldId)) {
            $orgs->join('invest_fields', 'invest_fields.org_id', '=', 'invest_org.id');
            $orgs->join('fields', 'fields.id', '=', 'invest_fields.field_id');
            $orgs->where('fields.id', '=', $fieldId);
        }

        if (!empty($dist)) {

        }

        if (!empty($keyword)) {
            $orgs->orWhere('invest_org.invest_name', 'like', "%$keyword%");
            $orgs->orWhere('invest_org.invest_desc', 'like', "%$keyword%");
        }
        $orgs = $orgs->get();
        foreach ($orgs as $org) {
            $org['phases'] = $org->getPhasesByOrgId($org->id);
            $org['members'] = $org->getOrgMemberbyOrgId($org->id);
            $org['projects'] = $org->getProjectNameByOrgId($org->id);
        }

        return $this->buildResponse(trans('api.get_investor_more.success'), $orgs);
    }

    /**
     * 通过项目标志获取 投资记录
     * @return array|static[]
     */
    public function getInvestLogByProjectId()
    {
        $projectId = Input::get('proId');

        $InvestLogs = InvestLog::whereProjectId($projectId)->get();
        if ($InvestLogs) {
            foreach ($InvestLogs as $InvestLog) {
                if ($InvestLog->toUser())
                    $InvestLog['investor'] = UserInfo::whereId($InvestLog->user_id)->pluck('realname');
                if ($InvestLog->toInvestOrg())
                    $InvestLog['org'] = InvestOrg::whereId($InvestLog->org_id)->pluck('invest_name');
            }
        }
        return $this->buildResponse(trans('api.get_invest_log.success'), $InvestLogs);

    }

    /**
     * 删除 已经融资记录
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     * @throws \Exception
     */
    public function delInvestLogById()
    {
        $logId  = Input::get('logId');
        $res    = InvestLog::find($logId)->delete();
        if($res)
            return $this->buildResponse('api.del-invest-log.success' );
    }


}
